<?php
/**
 * 小程序内容展示API
 * 处理篇章、展项、展品的查询和展示
 */

require_once 'base.php';

class ContentAPI extends MiniappBase {
    
    /**
     * 获取所有篇章
     */
    public function getChapters() {
        $pagination = $this->paginate(
            $_GET['page'] ?? 1, 
            $_GET['limit'] ?? 20
        );
        
        try {
            // 获取篇章列表
            $sql = "SELECT id, name, english_name, brief, sort, created_at, updated_at 
                    FROM exhibit_one 
                    ORDER BY sort ASC, id ASC 
                    LIMIT {$pagination['limit']} OFFSET {$pagination['offset']}";
            
            $chapters = $this->db->fetchAll($sql);
            
            // 获取总数
            $countSql = "SELECT COUNT(*) as total FROM exhibit_one";
            $total = $this->db->fetchOne($countSql)['total'];
            
            // 为每个篇章添加展项数量
            foreach ($chapters as &$chapter) {
                $countSql = "SELECT COUNT(*) as count FROM exhibit_two WHERE one_id = ?";
                $chapter['exhibit_count'] = $this->db->fetchOne($countSql, [$chapter['id']])['count'];
                $chapter['created_at'] = $this->formatTime($chapter['created_at']);
                $chapter['updated_at'] = $this->formatTime($chapter['updated_at']);
            }
            
            $this->success([
                'list' => $chapters,
                'pagination' => [
                    'page' => $pagination['page'],
                    'limit' => $pagination['limit'],
                    'total' => intval($total),
                    'pages' => ceil($total / $pagination['limit'])
                ]
            ]);
            
        } catch (Exception $e) {
            $this->error('获取篇章失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取单个篇章详情
     */
    public function getChapter($id) {
        if (empty($id)) {
            $this->error('缺少篇章ID');
        }
        
        try {
            $sql = "SELECT * FROM exhibit_one WHERE id = ?";
            $chapter = $this->db->fetchOne($sql, [$id]);
            
            if (!$chapter) {
                $this->error('篇章不存在', 404);
            }
            
            // 获取展项数量
            $countSql = "SELECT COUNT(*) as count FROM exhibit_two WHERE one_id = ?";
            $chapter['exhibit_count'] = $this->db->fetchOne($countSql, [$id])['count'];
            
            // 获取多媒体文件
            $mediaSql = "SELECT id, type, url, title FROM exhibit_item WHERE exhibit_id = ? AND level = 1";
            $chapter['media'] = $this->db->fetchAll($mediaSql, [$id]);
            
            $chapter['created_at'] = $this->formatTime($chapter['created_at']);
            $chapter['updated_at'] = $this->formatTime($chapter['updated_at']);
            
            $this->success($chapter);
            
        } catch (Exception $e) {
            $this->error('获取篇章详情失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取篇章下的展项
     */
    public function getChapterExhibits($chapterId) {
        if (empty($chapterId)) {
            $this->error('缺少篇章ID');
        }
        
        $pagination = $this->paginate($_GET['page'] ?? 1, $_GET['limit'] ?? 20);
        
        try {
            $sql = "SELECT e2.*, e1.name as chapter_name 
                    FROM exhibit_two e2 
                    LEFT JOIN exhibit_one e1 ON e2.one_id = e1.id 
                    WHERE e2.one_id = ? 
                    ORDER BY e2.sort ASC, e2.id ASC 
                    LIMIT {$pagination['limit']} OFFSET {$pagination['offset']}";
            
            $exhibits = $this->db->fetchAll($sql, [$chapterId]);
            
            // 获取总数
            $countSql = "SELECT COUNT(*) as total FROM exhibit_two WHERE one_id = ?";
            $total = $this->db->fetchOne($countSql, [$chapterId])['total'];
            
            // 为每个展项添加展品数量
            foreach ($exhibits as &$exhibit) {
                $countSql = "SELECT COUNT(*) as count FROM exhibit_three WHERE two_id = ?";
                $exhibit['item_count'] = $this->db->fetchOne($countSql, [$exhibit['id']])['count'];
                $exhibit['created_at'] = $this->formatTime($exhibit['created_at']);
                $exhibit['updated_at'] = $this->formatTime($exhibit['updated_at']);
            }
            
            $this->success([
                'list' => $exhibits,
                'pagination' => [
                    'page' => $pagination['page'],
                    'limit' => $pagination['limit'],
                    'total' => intval($total),
                    'pages' => ceil($total / $pagination['limit'])
                ]
            ]);
            
        } catch (Exception $e) {
            $this->error('获取展项失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取所有展项
     */
    public function getExhibits() {
        $pagination = $this->paginate($_GET['page'] ?? 1, $_GET['limit'] ?? 20);
        $chapterId = $_GET['chapter_id'] ?? null;
        $search = $_GET['search'] ?? null;
        
        try {
            $sql = "SELECT e2.*, e1.name as chapter_name 
                    FROM exhibit_two e2 
                    LEFT JOIN exhibit_one e1 ON e2.one_id = e1.id 
                    WHERE 1=1";
            
            $params = [];
            
            if ($chapterId) {
                $sql .= " AND e2.one_id = ?";
                $params[] = $chapterId;
            }
            
            if ($search) {
                $sql .= " AND (e2.name LIKE ? OR e2.english_name LIKE ? OR e2.brief LIKE ?)";
                $searchParam = "%$search%";
                $params = array_merge($params, [$searchParam, $searchParam, $searchParam]);
            }
            
            $sql .= " ORDER BY e2.sort ASC, e2.id ASC 
                     LIMIT {$pagination['limit']} OFFSET {$pagination['offset']}";
            
            $exhibits = $this->db->fetchAll($sql, $params);
            
            // 获取总数
            $countSql = str_replace("SELECT e2.*, e1.name as chapter_name", "SELECT COUNT(*) as total", $sql);
            $countSql = preg_replace('/ORDER BY.*LIMIT.*/', '', $countSql);
            $total = $this->db->fetchOne($countSql, $params)['total'];
            
            foreach ($exhibits as &$exhibit) {
                $countSql = "SELECT COUNT(*) as count FROM exhibit_three WHERE two_id = ?";
                $exhibit['item_count'] = $this->db->fetchOne($countSql, [$exhibit['id']])['count'];
                $exhibit['created_at'] = $this->formatTime($exhibit['created_at']);
                $exhibit['updated_at'] = $this->formatTime($exhibit['updated_at']);
            }
            
            $this->success([
                'list' => $exhibits,
                'pagination' => [
                    'page' => $pagination['page'],
                    'limit' => $pagination['limit'],
                    'total' => intval($total),
                    'pages' => ceil($total / $pagination['limit'])
                ]
            ]);
            
        } catch (Exception $e) {
            $this->error('获取展项失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取单个展项详情
     */
    public function getExhibit($id) {
        if (empty($id)) {
            $this->error('缺少展项ID');
        }
        
        try {
            $sql = "SELECT e2.*, e1.name as chapter_name 
                    FROM exhibit_two e2 
                    LEFT JOIN exhibit_one e1 ON e2.one_id = e1.id 
                    WHERE e2.id = ?";
            
            $exhibit = $this->db->fetchOne($sql, [$id]);
            
            if (!$exhibit) {
                $this->error('展项不存在', 404);
            }
            
            // 获取展品数量
            $countSql = "SELECT COUNT(*) as count FROM exhibit_three WHERE two_id = ?";
            $exhibit['item_count'] = $this->db->fetchOne($countSql, [$id])['count'];
            
            // 获取多媒体文件
            $mediaSql = "SELECT id, type, url, title FROM exhibit_item WHERE exhibit_id = ? AND level = 2";
            $exhibit['media'] = $this->db->fetchAll($mediaSql, [$id]);
            
            $exhibit['created_at'] = $this->formatTime($exhibit['created_at']);
            $exhibit['updated_at'] = $this->formatTime($exhibit['updated_at']);
            
            $this->success($exhibit);
            
        } catch (Exception $e) {
            $this->error('获取展项详情失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取展项下的展品
     */
    public function getExhibitItems($exhibitId) {
        if (empty($exhibitId)) {
            $this->error('缺少展项ID');
        }
        
        $pagination = $this->paginate($_GET['page'] ?? 1, $_GET['limit'] ?? 20);
        
        try {
            $sql = "SELECT e3.*, e1.name as chapter_name, e2.name as exhibit_name 
                    FROM exhibit_three e3 
                    LEFT JOIN exhibit_one e1 ON e3.one_id = e1.id 
                    LEFT JOIN exhibit_two e2 ON e3.two_id = e2.id 
                    WHERE e3.two_id = ? 
                    ORDER BY e3.sort ASC, e3.id ASC 
                    LIMIT {$pagination['limit']} OFFSET {$pagination['offset']}";
            
            $items = $this->db->fetchAll($sql, [$exhibitId]);
            
            // 获取总数
            $countSql = "SELECT COUNT(*) as total FROM exhibit_three WHERE two_id = ?";
            $total = $this->db->fetchOne($countSql, [$exhibitId])['total'];
            
            foreach ($items as &$item) {
                $item['created_at'] = $this->formatTime($item['created_at']);
                $item['updated_at'] = $this->formatTime($item['updated_at']);
            }
            
            $this->success([
                'list' => $items,
                'pagination' => [
                    'page' => $pagination['page'],
                    'limit' => $pagination['limit'],
                    'total' => intval($total),
                    'pages' => ceil($total / $pagination['limit'])
                ]
            ]);
            
        } catch (Exception $e) {
            $this->error('获取展品失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取所有展品
     */
    public function getItems() {
        $pagination = $this->paginate($_GET['page'] ?? 1, $_GET['limit'] ?? 20);
        $chapterId = $_GET['chapter_id'] ?? null;
        $exhibitId = $_GET['exhibit_id'] ?? null;
        $search = $_GET['search'] ?? null;
        
        try {
            $sql = "SELECT e3.*, e1.name as chapter_name, e2.name as exhibit_name 
                    FROM exhibit_three e3 
                    LEFT JOIN exhibit_one e1 ON e3.one_id = e1.id 
                    LEFT JOIN exhibit_two e2 ON e3.two_id = e2.id 
                    WHERE 1=1";
            
            $params = [];
            
            if ($chapterId) {
                $sql .= " AND e3.one_id = ?";
                $params[] = $chapterId;
            }
            
            if ($exhibitId) {
                $sql .= " AND e3.two_id = ?";
                $params[] = $exhibitId;
            }
            
            if ($search) {
                $sql .= " AND e3.name LIKE ?";
                $params[] = "%$search%";
            }
            
            $sql .= " ORDER BY e3.sort ASC, e3.id ASC 
                     LIMIT {$pagination['limit']} OFFSET {$pagination['offset']}";
            
            $items = $this->db->fetchAll($sql, $params);
            
            // 获取总数
            $countSql = str_replace("SELECT e3.*, e1.name as chapter_name, e2.name as exhibit_name", "SELECT COUNT(*) as total", $sql);
            $countSql = preg_replace('/ORDER BY.*LIMIT.*/', '', $countSql);
            $total = $this->db->fetchOne($countSql, $params)['total'];
            
            foreach ($items as &$item) {
                $item['created_at'] = $this->formatTime($item['created_at']);
                $item['updated_at'] = $this->formatTime($item['updated_at']);
            }
            
            $this->success([
                'list' => $items,
                'pagination' => [
                    'page' => $pagination['page'],
                    'limit' => $pagination['limit'],
                    'total' => intval($total),
                    'pages' => ceil($total / $pagination['limit'])
                ]
            ]);
            
        } catch (Exception $e) {
            $this->error('获取展品失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取单个展品详情
     */
    public function getItem($id) {
        if (empty($id)) {
            $this->error('缺少展品ID');
        }
        
        try {
            $sql = "SELECT e3.*, e1.name as chapter_name, e2.name as exhibit_name 
                    FROM exhibit_three e3 
                    LEFT JOIN exhibit_one e1 ON e3.one_id = e1.id 
                    LEFT JOIN exhibit_two e2 ON e3.two_id = e2.id 
                    WHERE e3.id = ?";
            
            $item = $this->db->fetchOne($sql, [$id]);
            
            if (!$item) {
                $this->error('展品不存在', 404);
            }
            
            // 获取多媒体文件
            $mediaSql = "SELECT id, type, url, title FROM exhibit_item WHERE exhibit_id = ? AND level = 3";
            $item['media'] = $this->db->fetchAll($mediaSql, [$id]);
            
            $item['created_at'] = $this->formatTime($item['created_at']);
            $item['updated_at'] = $this->formatTime($item['updated_at']);
            
            $this->success($item);
            
        } catch (Exception $e) {
            $this->error('获取展品详情失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取多媒体文件
     */
    public function getMedia($id) {
        if (empty($id)) {
            $this->error('缺少媒体ID');
        }
        
        try {
            $sql = "SELECT * FROM exhibit_item WHERE id = ?";
            $media = $this->db->fetchOne($sql, [$id]);
            
            if (!$media) {
                $this->error('媒体文件不存在', 404);
            }
            
            $media['created_at'] = $this->formatTime($media['created_at']);
            $this->success($media);
            
        } catch (Exception $e) {
            $this->error('获取媒体文件失败: ' . $e->getMessage());
        }
    }
}

// 处理请求
$content = new ContentAPI();

$method = $_SERVER['REQUEST_METHOD'];
$pathInfo = $_SERVER['PATH_INFO'] ?? '';
$action = $_GET['action'] ?? '';

if ($method === 'GET') {
    switch ($action) {
        case 'chapters':
            $content->getChapters();
            break;
        case 'chapter':
            $content->getChapter($_GET['id'] ?? '');
            break;
        case 'chapter_exhibits':
            $content->getChapterExhibits($_GET['chapter_id'] ?? '');
            break;
        case 'exhibits':
            $content->getExhibits();
            break;
        case 'exhibit':
            $content->getExhibit($_GET['id'] ?? '');
            break;
        case 'exhibit_items':
            $content->getExhibitItems($_GET['exhibit_id'] ?? '');
            break;
        case 'items':
            $content->getItems();
            break;
        case 'item':
            $content->getItem($_GET['id'] ?? '');
            break;
        case 'media':
            $content->getMedia($_GET['id'] ?? '');
            break;
        default:
            $content->error('无效的操作');
    }
} else {
    $content->error('不支持的请求方法');
}
?>